package com.yy.wga.mp.common.aop;

import cn.hutool.core.annotation.AnnotationUtil;
import com.alibaba.fastjson.JSON;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.mp.common.enmus.EOauthRespCode;
import com.yy.wga.mp.common.interceptor.RequestUserHolder;
import com.yy.wga.mp.common.utils.http.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * description
 *
 * @author <a href="mailto:ludezh@dingtalk.com"> ludezh </a>
 * @version 1.0.0   2018/12/27,10:14
 * @since 1.0.0     2018/12/27,10:14
 */
@Slf4j
@Aspect
@Component
public class ControllerAOP {

    /**
     * controller层切点
     */
    @Pointcut("execution(* com.yy.wga.mp.module.*.controller.*.*(..))")
    public void controllerPointcut() {
    }

    /**
     * controller层切点
     */
    @Pointcut("execution(* com.yy.wga.mp.module.*.controller.*.*.*(..))")
    public void controllerPointcut1() {
    }

    @Around("controllerPointcut() || controllerPointcut1()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 登录校验
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        NotLogin classAnnotation = AnnotationUtil.getAnnotation(pjp.getTarget().getClass(), NotLogin.class);
        NotLogin annotation = method.getAnnotation(NotLogin.class);
        if ((annotation == null && classAnnotation == null)
                && RequestUserHolder.getUserCache() == null) {
            throw new BusinessException(EOauthRespCode.SESSION_ID_INVALID);
        }

        // 日志打印
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        Object[] args = pjp.getArgs();
        log.info("################# url：{},参数：{}", request.getRequestURI(), Arrays.toString(args));
        Object proceed = pjp.proceed();
        log.info("################# 请求结果返回值：{}", JSON.toJSONString(proceed));
        return proceed;
    }
}
